<template>
    <div class="position-management-container">
        <h2 class="page-title">岗位管理</h2>

        <el-card class="table-card">
            <div class="table-header">
                <div class="table-title"></div>
                <div class="table-actions">
                    <!-- 新建按钮 -->
                    <el-button type="primary" @click="showDialog('create')">
                        <el-icon><Plus /></el-icon>
                        新建
                    </el-button>

                    <!-- 刷新按钮 -->
                    <div class="action-item" @mouseenter="showTooltip('刷新')" @mouseleave="hideTooltip">
                        <el-button :icon="Refresh" text @click="fetchData" />
                        <div v-if="tooltipContent === '刷新'" class="custom-tooltip">刷新</div>
                    </div>

                    <!-- 密度设置 -->
                    <div class="action-item">
                        <el-dropdown trigger="click" @command="handleDensityChange">
                            <el-button :icon="Menu" text />
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item
                                        command="default"
                                        :class="{ 'active': tableSize === 'default' }"
                                    >
                                        <el-icon v-if="tableSize === 'default'"><Check /></el-icon>
                                        默认
                                    </el-dropdown-item>
                                    <el-dropdown-item
                                        command="medium"
                                        :class="{ 'active': tableSize === 'medium' }"
                                    >
                                        <el-icon v-if="tableSize === 'medium'"><Check /></el-icon>
                                        中等
                                    </el-dropdown-item>
                                    <el-dropdown-item
                                        command="small"
                                        :class="{ 'active': tableSize === 'small' }"
                                    >
                                        <el-icon v-if="tableSize === 'small'"><Check /></el-icon>
                                        紧凑
                                    </el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>

                    <!-- 列设置 -->
                    <div class="action-item">
                        <el-popover placement="bottom" width="200" trigger="click">
                            <template #reference>
                                <el-tooltip content="列设置" placement="top">
                                    <el-button :icon="Setting" text />
                                </el-tooltip>
                            </template>
                            <el-checkbox-group v-model="checkedColumns">
                                <div class="column-item">
                                    <el-checkbox value="name">名称</el-checkbox>
                                </div>
                                <div class="column-item">
                                    <el-checkbox value="createTime">创建时间</el-checkbox>
                                </div>
                            </el-checkbox-group>
                        </el-popover>
                    </div>
                </div>
            </div>

            <div class="table-wrapper">
                <el-table
                    :data="positions"
                    style="width: 100%"
                    :size="tableSize"
                    v-loading="loading"
                    border
                    stripe
                    highlight-current-row
                >
                    <el-table-column
                        v-if="showColumn('name')"
                        prop="name"
                        label="名称"
                        min-width="200"
                    />
                    <el-table-column
                        v-if="showColumn('createTime')"
                        prop="createTime"
                        label="创建时间"
                        width="180"
                        sortable
                    >
                        <template #default="{ row }">
                            {{ formatDate(row.createTime) }}
                        </template>
                    </el-table-column>
                    <el-table-column
                        label="操作"
                        width="180"
                        fixed="right"
                        align="center"
                    >
                        <template #default="{ row, $index }">
                            <div class="action-buttons">
                                <el-button link type="primary" @click="showDialog('edit', row, $index)">
                                    编辑
                                </el-button>
                                <el-button link type="primary" @click="handleDelete($index)">
                                    删除
                                </el-button>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>

        <!-- 新建/编辑弹窗 -->
        <el-dialog
            v-model="dialogVisible"
            :title="dialogType === 'create' ? '新建岗位' : '编辑岗位'"
            width="500px"
        >
            <el-form :model="form" :rules="rules" ref="formRef">
                <el-form-item label="岗位名称" prop="name" label-width="80px">
                    <el-input
                        v-model="form.name"
                        placeholder="请输入岗位名称"
                        clearable
                    />
                </el-form-item>
                <el-form-item label="岗位描述" label-width="80px">
                    <el-input
                        v-model="form.description"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入岗位描述"
                        resize="vertical"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="submitting"
                >
                    {{ dialogType === 'create' ? '创建' : '保存' }}
                </el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import {
    Plus,
    Refresh,
    Menu,
    Setting,
    Check
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 模拟初始数据
const positions = ref([
    {
        id: 1,
        name: '前端开发工程师',
        description: '负责前端开发工作',
        createTime: new Date('2024-03-01').getTime()
    },
    {
        id: 2,
        name: '数据分析师',
        description: '负责数据统计分析',
        createTime: new Date('2024-03-05').getTime()
    }
])

// 表格设置
const tableSize = ref('default')
const checkedColumns = ref(['name', 'createTime'])
const loading = ref(false)

// 弹窗相关状态
const dialogVisible = ref(false)
const dialogType = ref('create')
const currentIndex = ref(-1)
const submitting = ref(false)
const formRef = ref(null)

// 表单数据
const form = reactive({
    name: '',
    description: ''
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '岗位名称不能为空', trigger: 'blur' },
        { min: 2, max: 20, message: '长度需在2到20个字符之间', trigger: 'blur' }
    ]
}

// 显示弹窗
const showDialog = (type, row, index) => {
    dialogType.value = type
    if (type === 'edit') {
        Object.assign(form, row)
        currentIndex.value = index
    } else {
        form.name = ''
        form.description = ''
        currentIndex.value = -1
    }
    dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
    try {
        await formRef.value.validate()
        submitting.value = true

        // 模拟API延迟
        await new Promise(resolve => setTimeout(resolve, 800))

        const newPosition = {
            id: Date.now(),
            name: form.name,
            description: form.description,
            createTime: Date.now()
        }

        if (dialogType.value === 'create') {
            positions.value.unshift(newPosition)
            ElMessage.success('创建成功')
        } else {
            positions.value.splice(currentIndex.value, 1, {
                ...positions.value[currentIndex.value],
                ...form
            })
            ElMessage.success('修改成功')
        }

        dialogVisible.value = false
    } catch (err) {
        // 验证失败不处理
    } finally {
        submitting.value = false
    }
}

// 删除岗位
const handleDelete = (index) => {
    ElMessageBox.confirm('确定要删除该岗位吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        positions.value.splice(index, 1)
        ElMessage.success('删除成功')
    })
}

// 日期格式化
const formatDate = (timestamp) => {
    return new Date(timestamp).toLocaleDateString() + ' ' +
        new Date(timestamp).toLocaleTimeString()
}

// 加载数据
const fetchData = async () => {
    loading.value = true
    try {
        // 模拟API请求
        await new Promise(resolve => setTimeout(resolve, 800))
    } finally {
        loading.value = false
    }
}

// 密度设置
const handleDensityChange = (size) => {
    tableSize.value = size
}

// 列显示控制
const showColumn = (colName) => {
    return checkedColumns.value.includes(colName)
}
</script>

<style scoped>
.position-management-container {
    padding: 20px;
    height: 100vh;
    box-sizing: border-box;
}

.table-card {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.table-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 10px;
    margin-bottom: 10px;
}

.table-actions {
    display: flex;
    gap: 12px;
    align-items: center;
}

.action-buttons {
    display: flex;
    gap: 12px;
    justify-content: center;
}

.el-button.link {
    padding: 0;
    color: #409EFF;
    text-decoration: underline;
    background: transparent;
}

.el-button.link:hover {
    color: #66b1ff;
    text-decoration: none;
}

.custom-tooltip {
    position: absolute;
    top: -40px;
    left: 50%;
    transform: translateX(-50%);
    background: #303133;
    color: white;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 12px;
    pointer-events: none;
}

.column-item {
    padding: 8px 12px;
}

@media (max-width: 768px) {
    .table-actions {
        flex-wrap: wrap;
        gap: 8px;
    }

    .el-button--primary {
        order: -1;
        width: 100%;
        margin-bottom: 8px;
    }

    .el-table__cell {
        padding: 8px !important;
    }
}
</style>